'''
Description: 
Author: 爱酱丶
Date: 2022-06-27 17:56:59
LastEditTime: 2023-03-15 18:13:15
LastEditors: 爱酱丶
'''
from multithreaddownload import FastDownloader

from requests.adapters import HTTPAdapter
import requests
import os


class PepsSentinelDownloader(object):
    
    # timeout = None
    auth = ('fengzhipo@outlook.com','3edc@WSX')
    search_url = "https://peps.cnes.fr/resto/api/collections/S2ST/search.json"
    
    def __init__(self,timeout=(60,60),usebar=True,pool_size=10):
        self.timeout=timeout
        self.usebar=usebar
        self.pool_size=pool_size
        return
    
    def __enter__(self):
        return self
    
    def searcher(self,tile,sdate,edate,cloud=100):
        params={"tileid":tile,"startDate":sdate,"completionDate":edate,"maxRecords":500}
        with requests.Session() as session:
            session.mount('http://', HTTPAdapter(max_retries=5))
            session.mount('https://', HTTPAdapter(max_retries=5))
            try: 
                respond=session.get(url=self.search_url,params=params,timeout=self.timeout)
                data = respond.json()
                i_s=[
                    i for i in range(len(data["features"]))
                    if data["features"][i]["properties"]["cloudCover"]>cloud]
                i_s.reverse() 
                for i in i_s: data["features"].pop(i) 
                respond.close()
                return data
            except requests.exceptions.RequestException as e: 
                print(e)
                return {}
            
    def downloader(self,productid,title,md5,folder):
        url=f"https://peps.cnes.fr/resto/collections/S2ST/{productid}/download/?issuerId=peps"
        path = os.path.join(folder,f"{title}.zip.incomplete")
        with FastDownloader(self.auth,usebar=self.usebar,max_time=25,block_size=1024*1024) as FD:
            FD.execute(url,path,md5,header_size=1024*1024,pool_size=self.pool_size,desc=title)
        os.rename(path,os.path.join(folder,f"{title}.zip"))
        return
      
    def tileDownloader(self,tile,sdate,edate,folder,cloud=100):
        result = []
        data = self.searcher(tile,sdate,edate,cloud)
        for i in range(len(data['features'])):
            title = data['features'][i]['properties']['title']
            md5 = data['features'][i]['properties']['resourceChecksum']
            pid = data['features'][i]['id']
            path = self.downloader(pid,title,md5,folder)
            result.append([title,path])
        return result
    
    def __exit__(self,_type,_value,_trace):
        return
    
